package cn.iocoder.yudao.module.trade.order.service.handler;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.module.api.infrastructure.notify.NotifyMessageSendApi;
import cn.iocoder.yudao.module.api.infrastructure.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.yudao.module.api.shop.admin.ShopUserApi;
import cn.iocoder.yudao.module.api.shop.admin.dto.ShopAdminRespDTO;
import cn.iocoder.yudao.module.api.trade.order.enums.TradeNotifySceneEnum;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderDO;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderItemDO;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息通知 {@link TradeOrderHandler} 实现类
 *
 * @author 山野羡民
 */
@Component
public class TradeOrderNotifyHandler implements TradeOrderHandler {

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private NotifyMessageSendApi notifyMessageSendApi;
    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private ShopUserApi shopUserApi;

    @Override
    public void afterPayOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        sendNotifyMessageWhenOrderPaid(order, orderItems);
    }

    private void sendNotifyMessageWhenOrderPaid(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        List<ShopAdminRespDTO> adminRespDTOS = shopUserApi.getShopAdminListByShopId(order.getShopId());
        if (CollUtil.isEmpty(adminRespDTOS)) {
            return;
        }
        adminRespDTOS.forEach(adminRespDTO -> {
            Map<String, Object> templateParams = new HashMap<>();
            templateParams.put("no", order.getNo());
            templateParams.put("payPrice", MoneyUtils.fenToYuanStr(order.getPayPrice()));
            if (CollUtil.isNotEmpty(orderItems)) {
                templateParams.put("spuName", orderItems.get(0).getSpuName());
            }
            if (adminRespDTO.getAdminUserId() != null && adminRespDTO.getAdminUserId() > 0) {
                notifyMessageSendApi.sendSingleMessageToAdmin(new NotifySendSingleToUserReqDTO()
                        .setUserId(adminRespDTO.getAdminUserId())
                        .setTemplateCode(TradeNotifySceneEnum.ORDER_PAY.getTemplateCode())
                        .setTemplateParams(templateParams));
            }
            if (adminRespDTO.getMemberUserId() != null && adminRespDTO.getMemberUserId() > 0) {
                notifyMessageSendApi.sendSingleMessageToMember(new NotifySendSingleToUserReqDTO()
                        .setUserId(adminRespDTO.getMemberUserId())
                        .setTemplateCode(TradeNotifySceneEnum.ORDER_PAY.getTemplateCode())
                        .setTemplateParams(templateParams));
            }
        });
    }

}
